package com.swotxu.screwweb.config;

import com.swotxu.screwweb.util.XmlConfigUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.Assert;

import javax.annotation.PostConstruct;

/**
 * @Date: 2021/7/13 10:40
 * @Author: xu.hai
 */
@Configuration
public class ScrewConfiguration {
    private static final Logger log = LoggerFactory.getLogger(ScrewConfiguration.class);

    @Value("${screw.confName:screw-db.xml}")
    private String confName;
    @Value("${screw.confPath:}")
    private String confPath;

    private volatile ScrewProperties screwProperties;

    @PostConstruct
    public void init() {
        reload();
    }

    public synchronized boolean reload() {
        String path = StringUtils.isNotBlank(confPath)? confPath : this.getClass().getClassLoader().getResource(confName).getPath();
        ScrewProperties bean = XmlConfigUtils.xml2bean(ScrewProperties.class, path);
        log.info("reload config: {}", bean);

        Assert.notNull(bean, "xml解析异常!");
        // 检查id是否唯一
        bean.toIdMap();
        // 检查最后生成的文件是否唯一
        bean.toSignatureMap();

        this.screwProperties = bean;
        return true;
    }

    public String getConfName() {
        return confName;
    }

    public void setConfName(String confName) {
        this.confName = confName;
    }

    public ScrewProperties getScrewProperties() {
        return screwProperties;
    }

    public void setScrewProperties(ScrewProperties screwProperties) {
        this.screwProperties = screwProperties;
    }
}
